let signature = require('./hb-signature');
let axios = require('axios')

class ApiResult{
    constructor(success,data){
        this.success = success;
        this.data = data;
    }
}
function parseResponse(res){
    if(res.status == 200){
        if(res.data.status == 'ok'){
            return new ApiResult(true,res.data.data);
        }else{
            return new ApiResult(false,JSON.stringify(res.data));
        }
    }else{
        return new ApiResult(false,'Error: '+JSON.stringify(res.data));
    }
}

function parseError(error){
    if(error.response){
        return new ApiResult(false,JSON.stringify(error.response.data));
    }else if(error.message){
        return new ApiResult(false,'Error: ' + error.message);
    }else{
        return new ApiResult(false,'Error: 未知错误！');
    }
}




async function getTimestamp(){
    let path = '/v1/common/timestamp';
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let url = baseUrl + path;
    try {
        let res = await axios.get(url);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}


async function getSymbols(){
    let path = '/v1/common/symbols';
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let url = baseUrl + path;
    try {
        let res = await axios.get(url);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}

async function getCurrencys(){
    let path = '/v1/common/currencys';
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let url = baseUrl + path;
    try {
        let res = await axios.get(url);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}


/**
 * 测试密钥
 * @param {} param 
 */
async function testKey(param){
    if(!param || !param.accessKey || !param.secretKey){
        return new ApiResult(false,'密钥不正确！');
    }
    param.host = 'https://' + param.host;
    let method = 'GET';
    let path = '/v1/account/accounts';
    let url = signature(param.accessKey,param.secretKey,method,param.host,path);
    try {
        let res = await axios.get(url);
        let result = parseResponse(res);
        if(result.success){
            result.data = true;
        }
        return result;
    } catch (error) {
        return parseError(error);
    }
}
async function getAccountId(){

    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }
    let method = 'GET';
    let path = '/v1/account/accounts';
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.get(url);
        let result = parseResponse(res);
        if(result.success){
            let list = result.data;
            for(let i in list){
                if(list[i].type == 'spot'){
                    result.data = list[i].id;
                    return result;
                }
            }
            return new ApiResult(false,'未对应账户ID！')
        }
        return result;
    } catch (error) {
        return parseError(error);
    }
}


async function getBalanceList(){
    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }

    let accountResult = await getAccountId();
    if(!accountResult.success){
        return accountResult;
    }

    let path = `/v1/account/accounts/${accountResult.data}/balance`;
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let method = 'GET';
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.get(url);
        let result = parseResponse(res);
        if(result.success){
            result.data = result.data.list;
            return result;
        }else{
            return result;
        }
    } catch (error) {
        return parseError(error);
    }
}

async function getOneBalance(param){
    if(!param){
        return;
    }
    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }

    let accountResult = await getAccountId();
    if(!accountResult.success){
        return accountResult;
    }
    let path = `/v1/account/accounts/${accountResult.data}/balance`;
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let method = 'GET';
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.get(url);
        let result = parseResponse(res);
        if(result.success){
            let list = result.data.list;
            for(let i in list){
                if(list[i].currency == param.currency){
                    return new ApiResult(true,list[i].balance)
                }
            }
            return new ApiResult(false,'无对应货币。');
        }else{
            return result;
        }
    } catch (error) {
        return parseError(error);
    }
}

/**
 * 
 * @param {*} param {
 *      symbol:'bttusdt',
 *      amount:'5'
 *      }
 */
async function buyByMarket(param){
    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }

    let accountResult = await getAccountId();
    if(!accountResult.success){
        return accountResult;
    }

    let defaultParam = {
        'account-id':accountResult.data,
        type:'buy-market',
        source:'spot-api',
    }

    let allParam = Object.assign({}, defaultParam, param);

    let path = `/v1/order/orders/place`;
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let method = 'POST';
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.post(url,allParam);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}

async function sellByMarket(param){
    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }

    let accountResult = await getAccountId();
    if(!accountResult.success){
        return accountResult;
    }

    let defaultParam = {
        'account-id':accountResult.data,
        type:'sell-market',
        source:'spot-api',
    }
    let allParam = Object.assign({}, defaultParam, param);

    let path = `/v1/order/orders/place`;
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let method = 'POST';
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.post(url,allParam);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}

async function getOrder(param){
    let accessKey = global.CONFIG.huobi.accessKey;
    let secretKey = global.CONFIG.huobi.secretKey;
    if(!accessKey || !secretKey){
        return new ApiResult(false,'未设置API密钥。')
    }

    let path = `/v1/order/orders/${param.orderId}`;
    let baseUrl = global.CONFIG.huobi.httpBaseUrl;
    let method = 'GET';
    let url = signature(accessKey,secretKey,method,baseUrl,path);
    try {
        let res = await axios.get(url);
        return parseResponse(res);
    } catch (error) {
        return parseError(error);
    }
}

module.exports = {
    testKey,
    getTimestamp,
    getSymbols,
    getCurrencys,
    getAccountId,
    getBalanceList,
    getOneBalance,
    buyByMarket,
    sellByMarket,
    getOrder,
}


